//
//  MyCloudView.m
//  UI_xiangmu
//
//  Created by dllo on 15/4/28.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "MyCloudView.h"

@interface MyCloudView ()

@property (nonatomic, retain) NSMutableArray *labels;

@end

@implementation MyCloudView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self awakeFromNib];
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    self.userInteractionEnabled = YES;
    self.minFontSize = 10;
    self.maxFontSize = 15;
}

- (UIColor *)randomColor {
    
    UIColor *co  = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];
    return co;
}

- (UIFont *)randomFont {
    return [UIFont systemFontOfSize:rand() % self.maxFontSize + self.minFontSize];
}

- (CGRect)randomFrameForLabel:(UILabel *)label {
    [label sizeToFit];
    CGFloat maxWidth = self.bounds.size.width - label.bounds.size.width;
    CGFloat maxHeight = self.bounds.size.height - label.bounds.size.height;
    
    return CGRectMake(random() % (NSInteger)maxWidth, random() % (NSInteger)maxHeight,
                      CGRectGetWidth(label.bounds), CGRectGetHeight(label.bounds));
}

- (BOOL)frameIntersects:(CGRect)frame {
    for (UILabel *label in self.labels) {
        if (CGRectIntersectsRect(frame, label.frame)) {
            return YES;
        }
    }
    return NO;
}

- (NSMutableArray *)labels {
    if (_labels == nil) {
        _labels = [NSMutableArray new];
    }
    return _labels;
}

- (void)generate {
    [self.labels makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self.labels removeAllObjects];
    NSInteger state = 0;
   for (int i = 0; i < 10; i++) {
        NSInteger num = self.titles.count;
        NSInteger j = arc4random()%num;
      
       NSString *str = self.titles[j];
       for (UILabel *label in self.labels) {
           if ([label.text isEqualToString:str]) {
               state = 1;
           }
        }
       if (state) {
           }else{
       assert([str isKindOfClass:[NSString class]]);
        UILabel *label = [[UILabel alloc] init];
        label.text = str;
        label.textColor = [self randomColor];
        label.font = [self randomFont];
        do {
            label.frame = [self randomFrameForLabel:label];
        } while ([self frameIntersects:label.frame]);
        
        [self.labels addObject:label];
        [self addSubview:label];
        
        UITapGestureRecognizer *tagGestue = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
        [label addGestureRecognizer:tagGestue];
        label.userInteractionEnabled = YES;
       }
    }

}

- (void)handleGesture:(UIGestureRecognizer*)gestureRecognizer {
    UILabel *label = (UILabel *)gestureRecognizer.view;
    if (self.tagClickBlock) {
        self.tagClickBlock(label.text,label.tag);
    }
}


@end
